
from flask import Flask    #导入Flask类
from flask import request
import openai
import json
from hashlib import sha1
from gevent import pywsgi
import xml.etree.ElementTree as ET
from WXBizMsgCrypt import WXBizMsgCrypt
from log import MyLogger

app=Flask(__name__)
weixin_appid = "微信appid"
app_seecret = "微信secret"
token = "wAky5xio"
EncodingAESKey = "微信加密key"
openai_key = "chat_gpt_key"
ai_log = MyLogger('./log/server.log', level='info')
@app.route('/')
def index():
    return 'welcome to andun chatgpt!'

@app.route('/chat.html',methods=['POST','GET'])
def chat():

    if request.method =="POST":
        prompt = request.form["prompt"]
    else:
        prompt = request.values.get("prompt")
    openai.api_key = openai_key

    response = openai.Completion.create(
        model='text-davinci-003',
        #prompt='研究中国古代文论时我应该知道的5个要点是什么？',
        prompt=prompt,
        temperature=0.3,
        max_tokens=800,
        top_p=1.0,
        frequency_penalty=0.0,
        presence_penalty=0.0,
    )
    #return response.response.choices[0].text
    ai_log.logger.info(response.response_ms)
    #data = json.dumps(response, ensure_ascii=False, encoding='utf-8')
    data = json.dumps(response)
    ai_log.logger.info(data)
    ai_log.logger.info(type(data))
    data = json.loads(data)
    result = data["choices"][0]
    ai_log.logger.info(result)
    ai_log.logger.info(result["text"])
    result = result["text"]
    #ai_log.logger.info(response.response)
    #d#ata = response.response.choices[0].text.decode('utf-8',"ignore")
    ai_log.logger.info(data)
    ai_log.logger.info(prompt)
    return result
def get_chat_content(ask_content):
    try:
        openai.api_key = openai_key

        response = openai.Completion.create(
            model='text-davinci-003',
            # prompt='研究中国古代文论时我应该知道的5个要点是什么？',
            prompt=ask_content,
            temperature=0.3,
            max_tokens=800,
            top_p=1.0,
            frequency_penalty=0.0,
            presence_penalty=0.0,
        )
        # return response.response.choices[0].text
        ai_log.logger.info(response.response_ms)
        # data = json.dumps(response, ensure_ascii=False, encoding='utf-8')
        data = json.dumps(response)
        ai_log.logger.info(data)
        ai_log.logger.info(type(data))
        data = json.loads(data)
        result = data["choices"][0]
        ai_log.logger.info(result)
        ask_content = result["text"]
        ai_log.logger.info(ask_content)
    except Exception as e:
        ai_log.logger.info("get_chat_content error", ask_content)
    return ask_content

def get_update(token, timestamp, nonce):
  arguments = ''
  for k in sorted([token, timestamp, nonce]):
    arguments = arguments + str(k)
  m = sha1()
  m.update(arguments.encode('utf8'))
  return m.hexdigest()

def check_signature():
  signature = request.args.get('signature', '')
  timestamp = request.args.get('timestamp', '')
  nonce = request.args.get('nonce', '')
  check = get_update(token, timestamp, nonce)
  ai_log.logger.info(f"check_signature {signature},{timestamp},{nonce},{check}")
  return True if check == signature else False

# def parse_xml(data):
#   try:
#     import xml.etree.cElementTree as ET
#   except ImportError:
#     import xml.etree.ElementTree as ET
dic_result = {}
def parse_xml(data):
    root = ET.fromstring(data)
    datas = '<xml>'
    ai_log.logger.info("parse_xml {datas}")
    for child in root:
        if child.tag == 'ToUserName':
            toUser = child.text
            datas += '<FromUserName>%s</FromUserName>' % toUser
        elif child.tag == 'FromUserName':
            fromUser = child.text
            datas += '<ToUserName>%s</ToUserName>' % fromUser
        elif child.tag == 'Content':
            datas += '<' + child.tag + '>'
            # if child.text in dic_result:
            #     result = dic_result[child.text]
            # else:
            #     result = get_chat_content(child.text)
            #     result = result.strip()
            #     dic_result["child.text"] = result
            result = child.text
            datas += result
            datas += '</' + child.tag + '>'
        else:
            datas += '<' + child.tag + '>'
            datas += child.text
            datas += '</' + child.tag + '>'
        ai_log.logger.info(f"child.tag is : {child.text}")
    datas += '</xml>'
    ai_log.logger.info(f"parse_xml end {datas}")
    return datas


@app.route('/weixin', methods=['GET', 'POST'])
def weixinInterface():
  if check_signature():
    if request.method == 'GET':
      echostr = request.args.get('echostr', '')
      return echostr
    elif request.method == 'POST':
      data = request.data
      #data = request.args.get('data', '')
      ai_log.logger.info(f"data is {data}")
      msg = parse_xml(data)
      ai_log.logger.info(f"xml is {msg}")
      return msg
  else:
    return 'signature error'

#实例化并命名为app实例
if __name__=="__main__":
    #app.run(port=2020,host="0.0.0.0",debug=False)
    server = pywsgi.WSGIServer(('0.0.0.0', 2020), app)
    server.serve_forever()
    ai_log.logger.info("started")